<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Child;
use App\Models\Game;
use App\Models\History;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AnalysisController extends BaseController
{
    public function issuccess()
    {
        return frontendView('analysis.issuccess', ['child_id' => 0]);
    }

    public function getsuccessdata($child_id = 0)
    {
        $user = $this->getUser();

        if ($child_id > 0) {
            $list = History::where("child_id", $child_id)->selectRaw('result, grade_id, count(id) as num')->with('grade')
                ->groupBy('result', 'grade_id')
                ->orderBy('grade_id')
                ->get();
        } else {
            $list = History::whereHas('child', function ($query) use ($user) {
                $query->where('user_id', $user->id);
            })->selectRaw('result, grade_id, count(id) as num')->with('grade')
                ->groupBy('result', 'grade_id')
                ->orderBy('grade_id')
                ->get();
        }


        $result = $tmp = [];
        foreach ($list as $v) {
            $tmp[$v->result][$v->grade_id] = $v->num;
        }
        for ($i = 0; $i < 2; $i++) {
            for ($j = 1; $j < 4; $j++) {
                isset($tmp[$i][$j]) || $tmp[$i][$j] = 0;
                $result[$i][] = $tmp[$i][$j];
            }
        }

        return response()->json(['status' => 200, 'data' => $result]);
    }

    public function basecount($child_id = 0)
    {
        $user = $this->getUser();
        $children = Child::where("user_id", $user->id)->get();
        $categories = Category::getArr();

        return frontendView('analysis.trainingcount', ['type' => 1, 'child_id' => $child_id, 'children' => $children, 'categories' => $categories]);
    }

    public function middlecount($child_id = 0)
    {
        $user = $this->getUser();
        $children = Child::where("user_id", $user->id)->get();
        $categories = Category::getArr();

        return frontendView('analysis.trainingcount', ['type' => 2, 'child_id' => $child_id, 'children' => $children, 'categories' => $categories]);
    }

    public function highcount($child_id = 0)
    {
        $user = $this->getUser();
        $children = Child::where("user_id", $user->id)->get();
        $categories = Category::getArr();

        return frontendView('analysis.trainingcount', ['type' => 3, 'child_id' => $child_id, 'children' => $children, 'categories' => $categories]);
    }

    /**
     *
     * @Date 2020/10/14 下午3:35
     * 旧版
     * @param int $type
     * @param int $child_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function gettrainingdata1($type = 1, $child_id = 0)
    {
        $user = $this->getUser();

        if (!in_array($type, [1, 2, 3])) {
            $type = 1;
        }
        //todu:暂时考虑所有记录，如果需要可以调整为成功记录，where('result', 1)
        if ($child_id > 0) {
            $list = History::where('child_id', $child_id)
                ->where('grade_id', $type)
                ->selectRaw('result, grade_id, game_id, count(id) as num')
                ->with('game')
                ->groupBy('result', 'grade_id', 'game_id')
                ->orderBy('num', 'desc')
                ->get();
        } else {
            $list = History::whereHas('child', function ($query) use ($user) {
                $query->where('user_id', $user->id);
            })
                ->where('grade_id', $type)
                ->selectRaw('result, grade_id, game_id, count(id) as num')
                ->with('game')
                ->groupBy('result', 'grade_id', 'game_id')
                ->orderBy('num', 'desc')
                ->get();
        }


        $result = ['x' => [], 'y' => [], 'z' => []];

        foreach ($list as $v) {
            $result['x'][] = $v->game->name;
            $result['y'][] = $v->num;
            //$result['z'][] = $v->game_id;
        }

        return response()->json(['status' => 200, 'data' => $result]);
    }

    /**
     *
     * @Date 2020/10/14 下午3:36
     * 新版本与家长端方式相同
     *
     * @param int $type
     * @param int $child_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function gettrainingdata($type = 1, $child_id = 0, Request $request)
    {
        $user = $this->getUser();
        $this->validate($request, [
            'child_id' => 'sometimes|exists:children,id',
            'grade_id' => 'sometimes|exists:grades,id',
            'category_id' => 'sometimes|exists:categories,id',
        ], [], [
            'child_id' => __("Student"),
            'category_id' => __("category"),
            'grade_id' => __("grade"),
        ]);

        $data = $request->only(['child_id', 'grade_id', 'category_id']);
        $data['user_id'] = $user->id;

        if (isset($data['child_id']) && $data['child_id'] > 0) {
            $child = Child::find($data['child_id']);
            if (!$this->allow('allow', $child)) {
                return response()->json(['status' => 405, 'data' => []]);
            }
        }

        $where = History::selectQuery($data);
        $history = History::where($where)
            ->selectRaw('result, grade_id, category_id, game_id, count(id) as num')
            ->groupBy('result', 'grade_id', 'game_id', 'category_id', 'game_id')
            ->orderBy('num', 'desc')
            ->get();

        $s = [];
        foreach ($history as $t) {
            $s[$t->game_id][$t->result] = $t->num;
        }

        $gameWhere = Game::selectQuery($data);

        $games = Game::where($gameWhere)->get();

        $result = ['labels' => [], 'successed' => [], 'failed' => []];

        foreach ($games as $v) {
            $result['labels'][] = $v->name;

            if (isset($s[$v->id]) && isset($s[$v->id][1])) {
                $result['successed'][] = $s[$v->id][1];
            } else {
                $result['successed'][] = 0;
            }

            if (isset($s[$v->id]) && isset($s[$v->id][0])) {
                $result['failed'][] = $s[$v->id][0];
            } else {
                $result['failed'][] = 0;
            }
        }


        if (count($result) == 0) {
            return response()->json(['status' => 400, 'data' => []]);
        }

        return response()->json(['status' => 200, 'data' => $result]);
    }

    public function view($id)
    {
        $training = History::find($id);
        if (empty($training)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        $user = $this->getUser();
        if (!$user->can("allow", $training->child)) {
            return back()->with('error', __("Sorry, you are not authorized to access this page."));
        }
        //dd($training);
        return frontendView('training.view', compact('training'));
    }

    public function delete($id)
    {
        $training = History::find($id);
        if (empty($training)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }
        $user = $this->getUser();
        if (!$user->can("allow", $training->child)) {
            return back()->with('error', __("Sorry, you are not authorized to access this page."));
        }
        if ($training->delete()) {
            return back()->with('success', __('Delete success'));
        }

        return back()->with('error', __('Delete failed'));
    }

    public function children(Request $request)
    {
        $user = $this->getUser();
        $query = $request->only(['child_name']);
        $query['user_id'] = $user->id;
        $where = Child::selectQuery($query);

        $list = Child::where($where)->orderBy('id', 'desc')->paginate(config('site.other.paginate'));
        $list = $list->appends($query);

        return frontendView('analysis.index', compact('list', 'user', 'query'));
    }

    public function assessment($child_id)
    {

        return frontendView('analysis.assessment', compact('child_id'));
    }


    public function childSuccess($child_id)
    {
        return frontendView("analysis.issuccess", ['child_id' => $child_id]);
    }
}
